<template>
  <view class="content">
    <scroll-view :scroll-y="true">
      <view class="tz-all">
        <view class="bg_content" @click="userSet">
          <view class="bgtop"></view>
          <image
            v-if="userInfo.avatar"
            :src="userInfo.avatar"
            mode="widthFix"
            class="avatar_user"
          ></image>
          <image
            v-else
            src="../../static/avatar.png"
            mode="widthFix"
            class="avatar_user"
          >
          </image>

          <view class="user-info">
            <button class="bun" v-if="userInfo.userName">
              {{ userInfo.userName }}
            </button>
            <button class="bun" v-else @click="userSet">设置用户信息</button>
            <view class="breeding_year">养龟经验: {{ userInfo.breedingYear }}</view>
          </view>

          <view v-if="userFeedbackHidden" class="popup_content">
            <view class="popup_title">个人设置</view>

            <div class="edit_avatar">
              <button
                class="avatar-btn"
                open-type="chooseAvatar"
                @chooseavatar="onChooseavatar"
              >
                <image
                  mode="widthFix"
                  class="edit_avatar_user"
                  :src="userInfo.avatar || '../../static/avatar.png'"
                ></image>
              </button>
            </div>
            <view class="popup_textarea_item">
              <input
                type="nickname"
                class="popup_textarea"
                v-model="userInfo.userName"
                placeholder="输入您的昵称"
              />

              <div class="inp_box">
                <view class="uni-list">
                  <view class="uni-list-cell">
                    <view class="uni-list-cell-left">何时开始养龟</view>
                    <view class="uni-list-cell-db">
                      <picker
                        mode="date"
                        :value="userInfo.date"
                        :start="startDate"
                        :end="endDate"
                        @change="bindDateChange"
                        fields="month"
                      >
                        <view class="uni-input date_text">{{
                          userInfo.date
                        }}</view>
                      </picker>
                    </view>
                  </view>
                </view>
              </div>

              <view @click="toSubmit" class="buttons">
                <text class="popup_button">确定</text>
              </view>
            </view>
          </view>
        </view>
        <view
          class="popup_overlay"
          v-show="userFeedbackHidden"
          @click="hideDiv"
        ></view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getDate } from '@/utils/date.js';
import { setCookie, getCookie } from '@/utils/cookie.js';
import { authRequest } from '@/utils/authRequest.js';
import { getLoginCode, getUserInfo } from '@/utils/auth.js';
// 响应式数据
const userFeedbackHidden = ref(false);
const nowTime = ref(getDate({ format: true }));

const userInfo = reactive({
  userName: '',
  date: getDate({ format: true }),
  breedingYear: 0,
  openidTEST: '',
  avatar: '',
});

// 计算属性
const startDate = computed(() => getDate('start'));
const endDate = computed(() => getDate('end'));

// 日期处理方法
const bindDateChange = (e) => {
  userInfo.date = e.detail.value;
  userInfo.breedingYear = getTurtleYear(userInfo.date);
};

const getTurtleYear = (date) => {
  if (judgeDate(`${date}-01`) < 0) {
    uni.showToast({ title: '选择日期不能大于当前日期', icon: 'none' });
    userInfo.date = getDate({ format: true });
    return;
  }

  const nowArr = (nowTime.value + '-01').split('-').map(Number);
  const dateArr = (date + '-01').split('-').map(Number);

  const y = Math.abs(nowArr[0] - dateArr[0]);
  const m = nowArr[1] - dateArr[1];

  return `${y ? y + '年' : ''}${m ? Math.abs(m) + '个月' : ''}`;
};

const judgeDate = (date) => new Date().getTime() - new Date(date).getTime();

// 弹窗控制
const userSet = () => (userFeedbackHidden.value = true);
const hideDiv = () => (userFeedbackHidden.value = false);

// 提交处理
const toSubmit = async () => {
  try {
    const res = await authRequest('setUser', {
      user_name: userInfo.userName,
      date: userInfo.date,
      breeding_year: userInfo.breedingYear,
      user_id: userInfo.openidTEST,
      avatar: userInfo.avatar,
    });
    
    uni.showToast({ title: '修改成功', icon: 'success' });
    userFeedbackHidden.value = false;
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({ title: '提交失败，请重试', icon: 'none' });
  }
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 登录并获取openid
    const loginInfo = await getLoginCode();
    userInfo.openidTEST = loginInfo.openid;
    
    // 获取用户详细信息
    const userData = await getUserInfo(loginInfo.openid);
    if (userData) {
      Object.assign(userInfo, {
        userName: userData.user_name,
        date: userData.date,
        breedingYear: userData.breeding_year,
        avatar: userData.avatar || userInfo.avatar,
      });
    } else {
      console.log('未找到用户信息，可能是新用户');
    }
    uni.hideLoading();
  } catch (error) {
    console.error('获取用户信息失败:', error);
    uni.showToast({ title: '获取用户信息失败', icon: 'none' });
  }
};

// 选择头像
const onChooseavatar = (e) => {
  new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: e.detail.avatarUrl,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    });
  })
    .then((res) => {
      return Promise.resolve({
        tempFilePath: e.detail.avatarUrl,
      });
    })
    .then(async (res) => {
      const random = Math.floor(Math.random() * 10000);
      const uploadRes = await uniCloud.uploadFile({
        filePath: res.tempFilePath,
        cloudPath: `${Date.now()}-AvatarImage-${random}`
      })
      userInfo.avatar = uploadRes.fileID;
      await authRequest("addImage", {
        imageUrl: uploadRes.fileID,
        createTime: Date.now()
      })
    })
    .catch((err) => {
      (userInfo.avatar = '')
      console.log(err, 'err');
    }); // 失败恢复
};

// 生命周期
onLoad(async () => {
  uni.showLoading({
    title: '加载中...',
    mask: true
  })
  await fetchUserInfo();
});
</script>

<style lang="less">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  // height: calc(100vh);
  position: relative;

  .back {
    position: fixed;
    top: 20upx;
    left: 20upx;
    width: 70upx;
    height: 70upx;
    z-index: 999;

    &::after {
      content: ' ';
      width: 20upx;
      height: 20upx;
      border-top: solid 1px #fff;
      border-right: solid 1px #fff;
      transform: rotate(-135deg);
      position: absolute;
      top: 20upx;
      left: 20upx;
    }
  }

  scroll-view {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    height: calc(100vh);

    .tz-all {
      width: 100%;
      min-height: 100vh;
      position: relative;

      .bgtop {
        width: 100%;
        height: 330rpx;
        background: #3d836d;
        display: block;
        border-bottom-left-radius: 50rpx;
        border-bottom-right-radius: 50rpx;
        color: #fff;
        padding-left: 100rpx;
        box-sizing: border-box;
      }

      .avatar {
        width: 200rpx;
        position: absolute;
        top: 4upx;
        left: calc(50% - 100upx);
      }

      .avatar-con {
        width: 200rpx;
        height: 200rpx;
        border-radius: 50%;
        overflow: hidden;
        position: absolute;
        top: 64upx;
        left: calc(50% - 50upx);
      }

      .user-info {
        color: #fff;
        width: 100%;
        position: absolute;
        top: 170upx;
        left: 0;
        display: flex;
        flex-direction: column;
        text-align: left;
        font-size: 32upx;
        align-items: center;

        .nickname {
          padding-right: 15upx;
          border-right: solid 1px #036260;
          font-weight: bold;
        }

        .phone {
          padding-left: 0;
          color: #ffffff;
          font-weight: bold;
        }

        image {
          width: 20upx;
          margin-left: 10upx;
        }
      }

      .bun {
        width: 250upx;
        background: none;
        border-radius: 50upx;
        color: #fff;
        font-size: 30upx;
        text-align: center;
        margin: 20upx auto;
        line-height: 50upx;

        &::after {
          display: none;
        }
      }

      .buns {
        width: 250upx;
        background: #ff8029;
        border-radius: 50upx;
        color: #fff;
        font-size: 30upx;
        text-align: center;
        margin: 50upx auto;
        line-height: 90upx;
      }

      .blank {
        width: 100%;
        height: 40upx;
      }
    }
  }

  .avatar_user {
    width: 160rpx;
    position: absolute;
    top: 20upx;
    left: calc(50% - 80upx);
    border-radius: 50%;
  }

  // 弹窗组件
  .popup_overlay {
    position: fixed;
    top: 0%;
    left: 0%;
    width: 100%;
    height: 100%;
    background-color: black;
    // z-index: 1001;
    -moz-opacity: 0.8;
    opacity: 0.8;
    filter: alpha(opacity=88);
  }

  .popup_content {
    display: flex;
    flex-direction: column;
    align-content: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80%;
    height: 760rpx;
    padding-bottom: 30rpx;
    border-radius: 16rpx;
    border: 10px solid white;
    box-sizing: border-box;
    background-color: white;
    z-index: 999;

    .popup_title {
      width: 100%;
      text-align: center;
      font-size: 32rpx;
    }

    .popup_textarea_item {
      padding-top: 5rpx;
      height: 80rpx;
      border-radius: 10rpx;
      width: 100%;
      background-color: #f1f1f1;
      margin-top: 20rpx;
    }

	.edit_avatar {
        display: flex;
        justify-content: center;
        align-items: center;
		padding-top: 20rpx;

        .avatar-btn {
			width: 160rpx;
			height: 160rpx;
			overflow: hidden;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 0;

			.edit_avatar_user {
				width: 160rpx;
				height: 160rpx;
			}
		}
	}

    .popup_textarea {
      width: 100%;
      height: 100%;
      font-size: 26rpx;
      padding-left: 20rpx;
      padding-left: 10px;
    }

    .buttons {
      border-radius: 10rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      margin-top: 40rpx;
      background-color: #036260;
      color: #fff;
    }

    // 时间picker
    .inp_box {
      padding-top: 30rpx;

      .uni-list-cell-left {
        padding-bottom: 10rpx;
      }

      .uni-list-cell-db {
        width: 100%;
        height: 41px;
        line-height: 41px;
        border-radius: 4px;
        border: 1px solid #e5e5e5;
        color: #999;
        padding-left: 10px;
        box-sizing: border-box;
      }
    }
  }
}
</style>
